﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _11.BinarySearchIndexAlgorithm
{
    class BinarySearchIndexAlgorithm
    {
        static void Main(string[] args)
        {
            Console.Write("N:");
            int n = int.Parse(Console.ReadLine());

            int[] numbers = new int[n];
            for (int i = 0; i < n; i++)
            {
                Console.Write("num[{0}]: ", i);
                numbers[i] = int.Parse(Console.ReadLine());
            }

            Array.Sort(numbers);
            Console.Write("Value:");
            int value = int.Parse(Console.ReadLine());

            int middleNumbers = numbers.Length / 2;
            int startNumbers = 0;
            int endNumbers = numbers.Length - 1;
            int lengthNumbers = numbers.Length;

            while (startNumbers != endNumbers)
            {
                if (numbers[middleNumbers] < value)
                {
                    startNumbers = middleNumbers + 1;
                }
                else if (numbers[middleNumbers] > value)
                {
                    endNumbers = middleNumbers - 1;
                }
                else
                {
                    break;  
                }
                lengthNumbers = startNumbers + endNumbers + 1;
                middleNumbers = lengthNumbers / 2;
            }

            if (startNumbers == endNumbers)
            {
                if (numbers[middleNumbers] == value)
                {
                    Console.WriteLine("Value: {0} Index: {1}",value,middleNumbers);
                }
                else
                {
                    Console.WriteLine("Not found!");
                }
            }
            else
            {
                Console.WriteLine("Value:{0} Index: {1}",value,middleNumbers-1);
            }
            //or
            int indexWithReadyFunc = Array.BinarySearch(numbers, value);
            Console.WriteLine("With function Array.BinarySearch(numbers, value):");

            if (indexWithReadyFunc >= 0)
            {
                Console.Write(" index: " + indexWithReadyFunc);
                Console.WriteLine();
            }
            else
            {
                Console.WriteLine("Not found! (with ready function)");
            }
        }
    }
}